package lxs.swift.tool;

import lxs.swift.instance.Chain;
import lxs.swift.instance.StructInstance;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Formatter {
    private static final Pattern PATTERN = Pattern.compile("\\\\?\\{\\w+}");

    /**
     * <p>"aaa{}",[1,2,3] =>"aaa1"</p>
     */
    public static String fmt(String pattern, Object... values) {
        Matcher matcher = PATTERN.matcher(pattern);
        StringBuffer sb = new StringBuffer();
        int i = 0;
        while (matcher.find()) {
            String param = matcher.group();
            if (param.startsWith("\\")) {
                matcher.appendReplacement(sb, param.substring(1));
                continue;//转义跳过
            }
            Object value = values[i++];
            matcher.appendReplacement(sb, value == null ? "null" : value.toString());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 根据map取值
     * <p>Formatter.fmtMap("aaa{name}",Map{"name":1})<p/>
     * <p>return "aaa1"<p/>
     */
    public static String fmtMap(String pattern, Map<String, Object> map) {
        Matcher matcher = PATTERN.matcher(pattern);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String param = matcher.group();
            if (param.startsWith("\\")) {
                matcher.appendReplacement(sb, param.substring(1));
                continue;//转义跳过
            }
            Object value = map.get(param.substring(2, param.length() - 1));
            matcher.appendReplacement(sb, value == null ? "null" : value.toString());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 根据obj 和路径智能取值
     * <p>Formatter.fmtSmart("aaa{name.name[0]}",JSON{"name":{"name":[1,2,3]}})<p/>
     * <p>return "aaa1"<p/>
     */
    public static String fmtSmart(String pattern, Object object) {
        Matcher matcher = PATTERN.matcher(pattern);
        StringBuffer sb = new StringBuffer();
        StructInstance<?> instance = StructInstance.from(object);
        while (matcher.find()) {
            String param = matcher.group();
            if (param.startsWith("\\")) {
                matcher.appendReplacement(sb, param.substring(1));
                continue;//转义跳过
            }
            String inner = param.substring(1, param.length() - 1);
            Chain chain = Chain.parse(inner);
            Object value = chain.read(instance);
            matcher.appendReplacement(sb, value == null ? "null" : value.toString());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
